<?
    require_once("Net/IPv4.php");

    class viewbycompanyController extends Principio_Library_ControllerAction
    {
	    public function init()
	    {
            parent::init();

	        $this->view->menu = array(
		        "Edit" => "edit",
		        "Customize profile" => "customize",
		        "Personal directory" => "personal",
		        "Delete " => "delete"
			);

            $this->view->hasAncestors = true;
	    }
	

	    public function indexAction()
	    {
	        $this->view->title = "Companies";
	    }
	
	
	    public function editAction()
	    {
	        if ($this->is_post)
	        {
                if ($this->checkPostItemInt("id", "Company ID"))
                {
                    $this->view->is_add = false;
                    $this->view->action = "edit";

                    $this->view->pools = Principio_Model_CompanyMapper::getByType(Principio_Model_CompanyMapper::TYPE_POOL);
                    $model_company_old = Principio_Model_CompanyMapper::get($this->post_data['id']);
                    $this->view->model_company = Principio_Model_CompanyMapper::get($this->post_data['id']);

                    if ($this->is_apply)
                    {
                        if ($this->validate())
                        {
                            switch ($model_company_old->getType())
                            {
                                case 1: // New type - company
                                    switch ($this->view->model_company->getType())
                                    {
                                        case 2: // Old type - pool
                                            Principio_Library_Common::checkValidity(Principio_Model_CompanyMapper::getAncestorsCount($this->view->model_company->getID()) == 0,
                                                                "Type of this pool can not be changed to company because of it has ancestors");
                                            break;

                                        case 1: // Old type - company, Ok
                                        case 3: // Old type - company in an existing pool, Ok
                                            break;
                                    };
                                    break;

                                case 2: // New type - pool
                                    switch ($this->view->model_company->getType())
                                    {
                                        case 1: // Old type - company
                                            break;

                                        case 2: // Old type - pool, Ok
                                        case 3: // Old type - company in an existing pool, Ok
                                            break;
                                    };
                                    break;

                                case 3: // New type - company in an existing pool
                                    switch ($this->view->model_company->getType())
                                    {
                                        case 2: // Old type - pool
                                            break;

                                        case 1: // Old type - company, Ok
                                        case 3: // Old type - company in an existing pool, Ok
                                            break;
                                    };
                                    break;
                            };
                            Principio_Model_CompanyMapper::save($this->view->model_company);
                            Principio_Library_DHCP::generate();
                            Principio_Library_Common::$msg = "Company was successfully updated";
                        };
                    };

                    if (Principio_Library_Common::$is_error)
                        $this->view->title = "View and Edit ".( ($model_company_old->isPool()) ? "pool" : "company")." [".$model_company_old->getCaption()."]";
                    else
                        $this->view->title = "View and Edit ".( ($this->view->model_company->isPool()) ? "pool" : "company")." [".$this->view->model_company->getCaption()."]";

                    $this->view->has_ancestors = (Principio_Model_CompanyMapper::getAncestorsCount($this->view->model_company->getID()) != 0);
                };
	        };
	    }
	
			
	    public function customizeAction()
	    {
            if (($this->is_post) && ($this->checkPostItemInt("id", "Company ID")))
            {
                if ($this->is_apply)
                {
                    $global_template = (isset($this->post_data['global_template']) ? $this->post_data['global_template'] : "");
                    $ext_template = (isset($this->post_data['ext_template']) ? $this->post_data['ext_template'] : "");

                    if (Principio_Model_CompanyMapper::updateTemplates($this->post_data['id'], $global_template, $ext_template) !== false)
                        Principio_Library_Common::$msg = "Templates were successfully updated";
                };

                $this->view->action = "customize";
                $this->view->model_company = Principio_Model_CompanyMapper::get($this->post_data['id']);
            };
        }
	
	
        public function personalAction()
        {
            if ($this->is_post)
            {
                if ($this->checkPostItemInt("id", "Company ID"))
                {
                    $this->view->model_company = Principio_Model_CompanyMapper::get($this->post_data['id']);
                    $this->view->action = "personal";
                };
            };
        }
	

        private function validateCIDR ()
        {
            $ip_mask_arr = explode("/", $this->view->model_company->getIP());
            Principio_Library_Common::checkValidity(count($ip_mask_arr) == 2, "Wrong IP/Mask.");

            if (Principio_Library_Common::$is_error)
                return false;

            Principio_Library_Common::checkValidity(Net_IPv4::validateIP($ip_mask_arr[0]), "Wrong IP address.");
            $networking = Principio_Library_IPCalculator::calculator($ip_mask_arr[0], $ip_mask_arr[1]);
            Principio_Library_Common::checkValidity(Net_IPv4::validateNetmask($networking['netmask']), "Wrong netmask.");

            if (Principio_Library_Common::$is_error)
                return false;

            $ip_calc = new Net_IPv4();
            $ip_calc->ip = $ip_mask_arr[0];
            $ip_calc->netmask = $networking['netmask'];
            Principio_Library_Common::checkValidity($ip_calc->calculate() === true, "Wrong IP/Mask.");

            if (Principio_Library_Common::$is_error)
                return false;

            $ranges = Principio_Model_CompanyMapper::getIPRanges2($this->view->model_company->getID());

            foreach ($ranges as $model_company)
            {
                $is_conflict = $ip_calc->ipInNetwork($model_company->getRangeFrom(), $ip_mask_arr[0]."/".$networking['netmask']);

                if ($is_conflict === false)
                    $is_conflict = $ip_calc->ipInNetwork($model_company->getRangeTo(), $ip_mask_arr[0]."/".$networking['netmask']);

                if ($is_conflict === false)
                {
                    list($ip,) = explode("/", $model_company->getIP());

                    $is_conflict = $ip_calc->ipInNetwork($networking['range_from'], $ip."/".$model_company->getNetmask());

                    if ($is_conflict === false)
                        $is_conflict = $ip_calc->ipInNetwork($networking['range_to'], $ip."/".$model_company->getNetmask());
                };

                Principio_Library_Common::checkValidity($is_conflict === false, "IP range [ ".$networking['range_from']." - ".$networking['range_to']." ] conflicts with company/pool '".$model_company->getCaption()."'   [ ".$model_company->getRangeFrom()." - ".$model_company->getRangeTo()." ]");
            };

            $this->view->model_company->setRangeFrom($networking['range_from'])
                                      ->setRangeTo($networking['range_to'])
                                      ->setDefaultGW($networking['default_gw'])
                                      ->setBroadcast($networking['broadcast'])
                                      ->setNetname($networking['netname'])
                                      ->setNetmask($networking['netmask']);

            return true;
        }
	

        private function validate()
        {
            // Common parameters for all company types
            if ($this->checkPostItemString("caption", "Caption"))
                $this->view->model_company->setCaption($this->post_data['caption']);

            if ($this->checkPostItemInt("company_type", "Company type"))
            {
                $this->view->model_company->setType($this->post_data['company_type']);
                Principio_Library_Common::checkValidity(($this->post_data['company_type'] < 4) && ($this->post_data['company_type'] > 0), "Bad company type");
            };


            if ($this->checkPostItem("vlan"))
            {
                if ($this->post_data['vlan'] != "")
                {
                    $this->view->model_company->setVlanID(intval($this->post_data['vlan']));
                    if ($this->view->model_company->getVlanID() != -1)
                        Principio_Library_Common::checkValidity(preg_match("/^[0-9]{0,}$/", $this->post_data['vlan']), "VLAN ID must be a number >= 0 (or empty)");
                };
            };

            if (($this->view->model_company->getVlanID() != -1) && ($this->checkPostItem("vlan_pc")))
            {
                if ($this->post_data['vlan_pc'] != "")
                {
                    $this->view->model_company->setVlanPcID($this->post_data['vlan_pc']);
                    if ($this->view->model_company->getVlanPcID() != -1)
                        Principio_Library_Common::checkValidity(preg_match("/^[0-9]{0,}$/", intval($this->post_data['vlan_pc'])), "VLAN PC ID must be a number >= 0 (or empty)");
                };
            };

            if ($this->checkPostItemString("proxy", "Proxy"))
                $this->view->model_company->setProxy($this->post_data['proxy']);


            switch ($this->view->model_company->getType())
            {
                case Principio_Model_Company::TYPE_COMPANY:
                case Principio_Model_Company::TYPE_POOL: // Pool
                    if ($this->checkPostItemString("ip", "IP/Mask"))
                    {
                        $this->view->model_company->setIP($this->post_data['ip']);
                        $this->validateCIDR($this->post_data);
                    };
                    break;

                case Principio_Model_Company::TYPE_COMPANY_IN_POOL:
                    if ($this->checkPostItemInt('pool_id', "Pool ID"))
                    {
                        $this->view->model_company->setPoolID($this->post_data['pool_id']);
                        Principio_Library_Common::checkValidity((count(Principio_Model_CompanyMapper::get($this->post_data['pool_id'])) > 0), "You have to select pool");
                    };
                    break;
            };


            if (!Principio_Library_Common::$is_error)
            {
                // Checks for unique
                Principio_Library_Common::checkValidity(Principio_Model_CompanyMapper::checkUniqueCaption($this->view->model_company), "Company or Pool with caption '".$this->view->model_company->getCaption()."' already exists");
            };

            return !Principio_Library_Common::$is_error;
        }


        /*
         *  Pool data
         */
        public function poolAction()
        {
            if ($this->is_post)
            {
                if ($this->checkPostItemInt("id", "Pool ID"))
                    $this->view->model_pool = Principio_Model_CompanyMapper::get($this->post_data['id']);
                else
                    $this->view->model_pool = new Principio_Model_Company();
            };
        }


        public function shortAction()
        {
            if ($this->is_post)
            {
                if ($this->checkPostItemInt("id", "Company ID"))
                {
                    $this->view->model_company = Principio_Model_CompanyMapper::get($this->post_data['id']);
                    if ($this->view->model_company->isCompanyInPool())
                        $this->view->model_pool = Principio_Model_CompanyMapper::get($this->view->model_company->getOwnerPoolId());

                    $this->view->title = "Overview of company [".$this->view->model_company->getCaption()."]";
                };
            };
        }


	    public function addAction()
	    {
	        if ($this->is_post)
	        {
                $this->view->title = "Add new company";
                $this->view->has_ancestors = false;
                $this->view->is_add = true;
                $this->view->action = "add";

                $this->view->pools = Principio_Model_CompanyMapper::getByType(Principio_Model_CompanyMapper::TYPE_POOL);
                $this->view->model_company = new Principio_Model_Company();

		        if ($this->is_apply)
		        {
                    if ($this->validate())
                    {
                        if (($company_id = Principio_Model_CompanyMapper::save($this->view->model_company)) !== false)
                        {
                            $this->view->model_company->setID($company_id);
                            Principio_Library_Common::$msg = "Company was added.";
                            Principio_Library_DHCP::generate();
                            $this->view->is_add = false;
                            $this->view->action = "edit";
                            $this->view->title = "View and Edit ".( ($this->view->model_company->isPool()) ? "pool" : "company")." [".$this->view->model_company->getCaption()."]";
                        };
				    };
		        }
                else
                {
                    if ((isset($this->post_data['pool_id'])) && (intval($this->post_data['pool_id']) > 0))
                        $this->view->model_company->setPoolID(intval($this->post_data['pool_id']))->setType(Principio_Model_Company::TYPE_COMPANY_IN_POOL);
                }
	        };
	    }
	
	
        public function deleteAction()
        {
            if (($this->is_post) && ($this->checkPostItemInt("id", "Company ID")))
            {
                $model_company = Principio_Model_CompanyMapper::get($this->post_data['id']);
                if (Principio_Model_CompanyMapper::delete($model_company))
                {
                    Principio_Library_DHCP::generate();
                    $this->view->title = "Deleting ".($model_company->isPool() ? "pool" : "company");
                    Principio_Library_Common::$msg = ($model_company->isPool() ? "Pool" : "Company")." [".$model_company->getCaption()."] was deleted.";
                };
            };
        }
}
